package com.lt.common;

import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Html;
import android.text.Spanned;

import com.lt.app.ResHelper;

/**
 * Created by tianlan on 2017/8/30.
 */

public class HtmlHelper {

    private static HtmlHelper instance;

    private HtmlHelper() {

    }

    public static HtmlHelper getInstance() {
        if (instance == null) {
            synchronized (HtmlHelper.class) {
                instance = new HtmlHelper();
            }
        }
        return instance;
    }

    public Spanned getSpannedFormHtml(String html) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
            } else {
                return Html.fromHtml(html);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getStringFormHtml(String html) {
        Spanned s = getSpannedFormHtml(html);
        return s == null ? html : s.toString();
    }


    public Spanned getImageSpannedFormHtml(String html) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY, new Html.ImageGetter() {
                @Override
                public Drawable getDrawable(String source) {
                    return getDrawableBySource(source);
                }
            }, null);
        } else {
            return Html.fromHtml(html, new Html.ImageGetter() {
                @Override
                public Drawable getDrawable(String source) {
                    return getDrawableBySource(source);
                }
            }, null);
        }
    }

    private Drawable getDrawableBySource(String source) {
        int resId = ConvertHelper.getInstance().getInt(source, 0);
        if (resId == 0) {
            return null;
        }
        Drawable drawable = ResHelper.getInstance().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        return drawable;
    }

    public String getHtmlImageString(int resId) {
        return "<img src='" + resId + "'>";
    }

    /**
     * @param color #eea6da
     * @return
     */
    public String getHtmlColorString(String color, String str) {
        return "<font color=\"" + color + "\">" + str + "</font>";
    }

    public String getHtmlColorString(int colorResId, String str) {
        return getHtmlColorString(ResHelper.getInstance().getColorStrByRes(colorResId), str);
    }

    public String getHtmlUnderLineString(String str) {
        StringBuilder sb = new StringBuilder();
        sb.append("<u>");
        sb.append(str);
        sb.append("</u>");
        return sb.toString();
    }
}
